import { useEffect, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAppDispatch, useAppSelector, type RootState } from '../../store/store';
import { fetchMedicalContent, clearContent } from '../../store/medicalContentSlice';
import styles from './contentList.module.scss';

interface ContentListProps {
  contentType: 'healthNews' | 'topicCheck' | 'lifeNews' | 'maternalNews' | 'debunkNews';
  channelId: string;
  title: string;
  showTabs?: boolean;
  tabs?: Array<{
    key: 'all' | 'audio' | 'qa' | 'article' | 'video';
    label: string;
    icon?: string;
  }>;
}

const ContentList = ({ 
  contentType, 
  channelId, 
  title, 
  showTabs = false,
  tabs = []
}: ContentListProps) => {
  const dispatch = useAppDispatch();
  const navigate = useNavigate();
  const { byKey, pageSize, isLoading, hasMore, bannerList } = useAppSelector((state: RootState) => state.medicalContent);
  
  const [activeTab, setActiveTab] = useState<'all' | 'audio' | 'qa' | 'article' | 'video'>('all');
  const sentinelRef = useRef<HTMLDivElement | null>(null);

  // 根据内容类型获取数据
  const getData = () => {
    // 对于所有内容类型，都使用 byKey 来获取数据，确保不同频道的数据不会互相覆盖
    const cacheKey = `${contentType}:${channelId}`;
    return (byKey as any)?.[cacheKey] || [];
  };

  const data = getData();

  const getRequestParams = (currentPage: number) => ({
    contentType: contentType as any,
    channel_id: channelId,
    page: currentPage,
    pageSize: 10,
    from_wx_mini: 'true',
    partner: 'chunyuyisheng',
    release_time: '180',
  });

  useEffect(() => {
    if (!data || data.length === 0) {
      dispatch(fetchMedicalContent(getRequestParams(1)));
    }

    return () => {
      dispatch(clearContent(contentType));
    };
  }, [dispatch, contentType, channelId]);

  const handleLoadMore = () => {
    if (isLoading || !hasMore) return;
    const size = pageSize || 10;
    const nextPage = Math.floor((data?.length || 0) / size) + 1;
    dispatch(fetchMedicalContent(getRequestParams(nextPage)));
  };

  // 无限滚动监听
  useEffect(() => {
    if (!hasMore) return;
    const target = sentinelRef.current;
    if (!target) return;

    const observer = new IntersectionObserver(
      (entries) => {
        const entry = entries[0];
        if (entry.isIntersecting) {
          handleLoadMore();
        }
      },
      {
        root: null,
        rootMargin: '200px 0px',
        threshold: 0.01,
      }
    );

    observer.observe(target);
    return () => {
      observer.unobserve(target);
      observer.disconnect();
    };
  }, [hasMore, isLoading, data.length]);

  // 过滤数据
  const getItemType = (item: any): 'audio' | 'qa' | 'article' | 'video' => {
    const ct = item?.topic_info?.content_type;
    if (ct === 2) return 'audio';
    if (ct === 3) return 'qa';
    if (ct === 4) return 'video';
    if (ct === 1) return 'article';
    if (item?.topic_info?.cover_image) return 'article';
    return 'article';
  };

  const filteredData = showTabs && activeTab !== 'all'
    ? data.filter((item: any) => getItemType(item) === activeTab)
    : data;

  // 渲染列表项
  const renderListItem = (item: any, index: number) => {
    if (contentType === 'topicCheck') {
      // 专家科普样式
      const title = item?.topic_info?.title || item?.title || item?.name || '';
      const doctorName = item?.doctor_info?.doctor_name || item?.doctor?.doctor_name || '';
      const hospitalName = item?.doctor_info?.hospital_name || item?.doctor?.hospital_name || '';
      const avatar = item?.doctor_info?.image || item?.doctor_info?.avatar || item?.image || '';
      const digest = item?.topic_info?.digest || '';
      const badge = item?.doctor_info?.tag || '';
      const position = item?.doctor_info?.title || '';
      const readNum = item?.read_num || '';
      
      return (
        <div key={`${item?.id}-${index}`} className={styles['news-item']}>
          <div className={styles['news-content']}>
            <p className={styles['news-title']}>{title}</p>
            {digest && <div className={styles['news-digest']}>{digest}</div>}
            <div className={styles['author-row']}>
              <img className={styles['avatar']} src={avatar || '/vite.svg'} alt={doctorName} />
              <span className={styles['author-name']}>{doctorName}</span>
              {badge && <span className={styles['badge']}>{badge}</span>}
              <span className={styles['author-desc']}>{position} {hospitalName}</span>
            </div>
            <div className={styles['footer-row']}>
              <span className={styles['chip']}># 图文</span>
              {readNum && <span className={styles['read']}>阅读{readNum}</span>}
            </div>
          </div>
        </div>
      );
    } else {
      // 其他内容样式
      return (
        <div 
          key={`${item?.id}-${index}`} 
          className={styles['news-item']}
          data-id={item?.id || item?.topic_info?.topic_id || item?.topic_info?.id || ''}
          data-link={item?.topic_info?.cy_redirect?.target_scheme || item?.cy_redirect?.target_scheme || ''}
        >
          <img src={item.image} alt={item.title} className={styles['news-img']} />
          <div className={styles['news-content']}>
            <h3 className={styles['news-title']}>{item.title}</h3>
            <div className={styles['news-meta']}>
              <span>{title} {item.date_str}</span>
            </div>
          </div>
        </div>
      );
    }
  };
  const handleItemClick = (e: React.MouseEvent<HTMLDivElement>) => {
    const target = e.target as HTMLElement
    const card = target.closest('.' + styles['news-item']) as HTMLElement | null
    if (!card) return
    const id = card.getAttribute('data-id') || ''
    const link = card.getAttribute('data-link') || ''
    // 先尝试走内链：跳到 /homedetail/:id
    if (id) {
      navigate(`/homedetail/${id}`)
      return
    }
    // 否则尝试外链，并追加 id 查询参数
    if (link) {
      try {
        const url = new URL(link)
        if (id) url.searchParams.set('id', id)
        window.location.href = url.toString()
        return
      } catch {}
    }
    // 如无外链，仅打印 id（避免引入新路由逻辑影响现有效果）
    if (id) {
      console.log('内容项ID:', id)
    }
  }

  return (
    <div className={styles['content-container']}>
      {/* 轮播图 */}
      {bannerList.length > 0 && (
        <div className="banner" >
          {bannerList.map((item, idx) => (
            <img key={idx} src={item.image} alt={`${title}-banner-${idx}`} />
          ))}
        </div>
      )}

      {/* 加载中提示 */}
      {isLoading && data.length === 0 && <div>加载{title}中...</div>}

      {/* Tabs */}
      {showTabs && tabs.length > 0 && (
        <div className={styles.tabs}>
          {tabs.map(tab => (
            <button 
              key={tab.key}
              className={`${styles.tab} ${activeTab === tab.key ? styles.active : ''}`} 
              onClick={() => setActiveTab(tab.key)}
            >
              {tab.icon && <span className={`${styles.icon} 
              ${styles[`icon${tab.key.charAt(0).toUpperCase() + tab.key.slice(1)}`]}`}></span>}
              {tab.label}
            </button>
          ))}
        </div>
      )}

      {/* 内容列表 */}
      {filteredData.length > 0 && (
        <div className={styles['news-list']} onClick={(e) => handleItemClick(e)}
        >
          {filteredData.map((item: any, index: number) => renderListItem(item, index))}
        </div>
      )}

      {/* 无限列表哨兵 */}
      <div ref={sentinelRef} style={{ height: 1 }} />

      {/* 加载中状态 */}
      {isLoading && data.length > 0 && <div>加载中...</div>}

      {/* 没有更多 */}
      {!hasMore && data.length > 0 && <div>没有更多了</div>}
    </div>
  );
};

export default ContentList;
